<template>
  <main>
    <!-- 登录表单 -->
    <form v-show="isLogin" class="login-form">
      <h3 class="loginTitle">欢迎回来</h3>
      <p class="form-subtitle">请登录您的账户</p>

      <label class="loginUsernameLabel">
        用户名
        <input type="text" v-model="userName" id="username" placeholder="您可以使用注册时使用的登录名称/邮箱/手机号"
               required class="loginUsernameInput">
      </label>

      <label class="loginPasswordLabel">
        密码
        <input type="password" v-model="userPassword" id="password" placeholder="请输入密码" required
               class="loginPasswordInput">
      </label>

      <div class="remember-me">
        <div class="bottom-buttons">
          <label class="loginRememberLabel">记住我
            <input type="checkbox" @click="keep" class="loginRememberCheckbox">
          </label>
        </div>
      </div>

      <div v-show="showKeepText" class="keep-login-section">
        <p class="keepLoginHint">保持登录时长设置</p>
        <div class="toggle-unit">
          <button type="button" class="toggle-unit-btn" @click="ToggleDay()">
            {{ isDay ? '切换为小时单位' : '切换为天单位' }}
          </button>
          <span class="toggleUnitText">(当前单位: {{ isDay ? '天' : '小时' }})</span>
        </div>
        <input type="number" v-model="keepLoginDay" min="0" :placeholder="isDay ? '请输入天数' : '请输入小时数'"
               class="loginKeepDurationInput">
      </div>

      <input type="button" @click="login" value="立即登录" class="primary-btn">

      <div class="form-footer">
        <a @click="loginOrRegister" class="loginToRegisterLink">还没有账号？立即注册</a>
      </div>
      <div class="bottom-buttons">
        <button @click="jump('src/page/home/index.html')" class="backHomeBtn">返回首页</button>
        <a @click="jump('src/page/safety/index.html')" class="forgotPasswordLink">忘记密码?</a>
      </div>
    </form>

    <!-- 注册表单 -->
    <form v-show="!isLogin" class="register">
      <h3 class="registerTitle">创建新账户</h3>
      <p class="form-notice">请注意：标有 <span class="required">*</span> 的为必填项</p>
      <p class="form-subtitle">未特别注明的情况下，其他用户无法看到您的信息</p>

      <small v-if="validationErrors.elseMxg" class="error-message">{{ validationErrors.elseMxg }}</small>


      <label class="registerUsernameLabel">
        用户名 <span class="required">*</span><span class="field-description">这将是您公开显示的名称</span>
        <input type="text" @blur="validateInput" v-model="userName" placeholder="设置您的用户名" required
               class="registerUsernameInput">
      </label>
      <small v-if="validationErrors.userName" class="error-message">{{ validationErrors.userName }}</small>


      <label class="registerLoginAccountLabel">
        登录使用名称/登录账号 <span
          class="required">*</span> <span class="field-description">您之后可以使用它来进行登录</span>
        <input type="text" @input="clsErrorMxg" @blur="validateInput" v-model="userNameLogin"
               placeholder="设置登录账号" required class="registerLoginAccountInput">
      </label>
      <small v-if="validationErrors.userNameLogin" class="error-message">{{ validationErrors.userNameLogin }}</small>

      <label class="registerPasswordLabel">
        密码 <span class="required">*</span>
        <input type="password" v-model="userPassword" @blur="validateInput" placeholder="设置安全密码" required
               class="registerPasswordInput">
      </label>
      <small v-if="validationErrors.userPassword" class="error-message">{{ validationErrors.userPassword }}</small>

      <label class="registerConfirmPasswordLabel">
        确认密码 <span class="required">*</span>
        <input type="password" v-model="confirmPassword" @blur="validateInput" placeholder="再次输入密码" required
               class="registerConfirmPasswordInput">
      </label>
      <small v-if="validationErrors.confirmPassword" class="error-message">
        {{ validationErrors.confirmPassword }}
      </small>

      <label class="registerEmailLabel">
        电子邮箱 <span class="required">*</span>
        <input type="text" @input="clsErrorMxg" @blur="validateInput" v-model="mailbox"
               placeholder="输入有效邮箱地址" required class="registerEmailInput">
      </label>
      <small v-if="validationErrors.mailbox" class="error-message">{{ validationErrors.mailbox }}</small>


      <label class="registerBioLabel">
        个人简介<span class="field-description">向其他用户展示您的个人介绍</span>
        <textarea v-model="user.bio" placeholder="简单介绍一下自己" class="registerBioInput"/>
      </label>


      <label class="registerSexLabel">
        性别<span class="field-description">请注意此信息将是公开的</span>
        <input type="text" v-model="user.sex" maxlength="15" placeholder="选填" class="registerSexInput">
      </label>


      <label class="registerBirthdayLabel">
        生日 <span class="field-description">请注意此信息将是公开的,如果您不想公开请保持默认即可</span>
        <input type="date" v-model="birthday" class="registerBirthdayInput">
      </label>

      <label class="registerPhoneLabel">
        手机号码
        <input type="text" @input="clsErrorMxg" @blur="validateInput" v-model="userPe"
               placeholder="选填" class="registerPhoneInput">
      </label>
      <small v-if="validationErrors.userPe" class="error-message">{{ validationErrors.userPe }}</small>

      <input type="button" :disabled="!canRegister" @click="register" value="立即注册" class="primary-btn">

      <div class="form-footer">
        <a @click="loginOrRegister" class="registerToLoginLink">
          已有账号？立即登录
        </a>
      </div>
      <div class="bottom-buttons">
        <button @click="jump('src/page/home/index.html')" class="backHomeBtn">返回首页</button>
        <a @click="jump('src/page/safety/index.html')" class="forgotPasswordLink">忘记密码?</a>
      </div>
    </form>
  </main>
  <Bottom/>
</template>
<script setup lang="ts">
import {ref, watch} from 'vue'
import {Users} from "@models/User.ts";
import axiosInstance from "@utils/axiosInstance.ts";
import {globalConst} from "@constants/globalConst.ts";
import ResponseResult from "@models/ReturnResult.ts";
import {isNull} from "@utils/stringUtil.ts";
import {setUser} from "@stores/localStorage.ts";
import {jump} from "@utils/router.ts";
import Bottom from "@components/bottom.vue";

// 定义 reactive 状态
const userName = ref('')
const userNameLogin = ref('')
const userPassword = ref('')
const userPe = ref('')
const mailbox = ref('')
const confirmPassword = ref('')
const birthday = ref('1970-01-01')
const user = ref(new Users())
user.value.birthday = new Date('birthday')
const validationErrors = ref({
  elseMxg: '',
  userPe: '',
  confirmPassword: '',
  mailbox: '',
  userPassword: '',
  userNameLogin: '',
  userName: ''
})
watch([birthday], ([]) => {
  console.log(user.value.birthday)
  user.value.birthday = new Date(birthday.value)
  console.log(user.value.birthday)
})
const canRegister = ref(false)
const isLogin = ref(true)
const showKeepText = ref(false)
const lastValidationTime = ref(0)
const validationInterval = ref(5000)
const isDay = ref(false)
const keepLoginDay = ref(0)
watch([confirmPassword, userPassword], ([]) => {
  if (confirmPassword.value === userPassword.value) {
    validationErrors.value.confirmPassword = ''
  } else {
    validationErrors.value.confirmPassword = '确认密码和输入的密码不一致'
  }
})

function loginOrRegister() {
  isLogin.value = !isLogin.value
}

function ToggleDay() {
  isDay.value = !isDay.value
}

function clsErrorMxg() {
  validationErrors.value = {
    elseMxg: '',
    userPe: '',
    confirmPassword: '',
    mailbox: '',
    userPassword: '',
    userNameLogin: '',
    userName: ''
  }
}

function keep() {
  showKeepText.value = !showKeepText.value
}

function validateInput() {
  if (!baseTest()) return
  const now = Date.now()
  if (now - lastValidationTime.value < validationInterval.value) {
    console.log('校验操作过于频繁，已跳过')
    return
  }
  clsErrorMxg()
  lastValidationTime.value = now
  axiosInstance.post(`${globalConst.baseUrl}login/testRegisterMxg`, {
    userNameLogin: userNameLogin.value,
    mailbox: mailbox.value,
    userPe: userPe.value,
  }).then(response => {
    const res = ResponseResult.fromApiResponse(response.data)
    canRegister.value = res.isSuccess()
    if (res.isSuccess()) {
      validationErrors.value.elseMxg = <string>res.msg
    } else {
      try {
        handleValidationErrors(res.returnResult)
      } catch (e) {
        validationErrors.value.elseMxg = <string>res.msg
      }
      const user0 = Users.fromApiResponse(res.returnResult)
      if (!user0.hasUserMsg()) {
        validationErrors.value.elseMxg = <string>res.msg
      } else {
        let c = true
        const m = '不可用,因为与其他用户使用的重复!'
        if (isNull(user0.userNameLogin)) {
          validationErrors.value.userNameLogin = m
          c = false
        }
        if (isNull(user0.mailbox)) {
          validationErrors.value.mailbox = m
          c = false
        }
        if (isNull(user0.userPe)) {
          validationErrors.value.userPe = m
          c = false
        }
        if (c) {
          validationErrors.value.elseMxg = <string>res.msg
        }
      }
    }
  }).catch(error => {
    console.error('校验请求失败', error)
    alert('校验请求失败，请稍后重试')
  })
}

function handleValidationErrors(error: Users) {
  try {
    // 解析后端传过来的错误信息字符串
    if (!isNull(error.mailbox)) {
      validationErrors.value.mailbox = "此邮箱已被其他用户使用!"
    }
    if (!isNull(error.userNameLogin)) {
      validationErrors.value.userNameLogin = "此登录名称已被其他用户使用!"

    }
    if (!isNull(error.userPe)) {
      validationErrors.value.userPe = "此手机号已被其他用户使用!"
    }
  } catch (error) {
    console.log('错误信息:' + error)//说明不是对象
  }
}

function login() {
  if (userName.value === '' || userPassword.value === '') {
    alert('登录凭据和密码不可为空!')
    return
  }
  if (userPassword.value.length < 6) {
    alert('密码长度至少6位!')
    return;
  }
  const url = `${globalConst.baseUrl}login/userLogin`
  if (keepLoginDay.value <= 0)
    keepLoginDay.value = 1
  axiosInstance.post(url, {
        userName: userName.value,
        userPassword: userPassword.value,
        unitIsDay: isDay.value,
        keepTime: keepLoginDay.value
      }
  ).then(response => {
    const result = response.data
    if (result.operationResult) {
      alert(result.msg)
      //更新信息
      try {
        setUser(Users.fromApiResponse(result.returnResult))
        jump('src/page/home/index.html')
      } catch (e) {
        alert('您登录成功了,但是用户信息解析失败!您在服务器上应该已经登录了,但是在客户端解析失败了,这个错误只会影响您客户端的显示,不会影响您的操作,如果您联系管理员请提供以下信息:' + e)
      }
    } else {
      alert('登录失败，' + result.msg)
    }
  }).catch(error => {
    console.error('登录请求失败', error)
    alert('登录请求失败，请稍后重试')
  })
}

function baseTest() {
  let flag = true
  //此处使用的是接近 RFC 5322 的邮箱验证规则
  const emailPattern = /^(?:(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*)|(?:".+"))@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}|(?:\[(?:\d{1,3}\.){3}\d{1,3}\]))$/
  if (userName.value === '') {
    flag = false
    validationErrors.value.userName = '此字段为必填!'
  }
  if (userPassword.value === '') {
    flag = false
    validationErrors.value.userPassword = '请填写密码!'
  } else if (userPassword.value.length < 6) {
    flag = false
    validationErrors.value.userPassword = '密码长度至少6位!'
  }
  if (userNameLogin.value === '') {
    flag = false
    validationErrors.value.userNameLogin = '此字段为必填!'
  }
  if (mailbox.value === '') {
    flag = false
    validationErrors.value.mailbox = '此字段为必填!'
  } else if (!emailPattern.test(mailbox.value)) {
    validationErrors.value.mailbox = '邮箱格式不正确！'
    flag = false
  }
  if (userPassword.value !== confirmPassword.value) {
    flag = false
    validationErrors.value.confirmPassword = '确认密码与密码不一致!'
  }
  return flag
}

function register() {
  if (!baseTest()) return
  if (!canRegister.value) {
    //立刻重置时间
    lastValidationTime.value = 114514//重置校验时间
    validateInput()
    if (!canRegister.value)//检查二次校验是否通过
      return
  }
  if (user.value.bio === '') {
    user.value.bio = 'ta没有留下任何简介'
  }
  axiosInstance.post(`${globalConst.baseUrl}login/userRegister`, {//到处应该没问题
    userName: userName.value,
    userNameLogin: userNameLogin.value,
    userPassword: userPassword.value,
    mailbox: mailbox.value,
    bio: user.value.bio,
    sex: user.value.sex,
    birthday: user.value.birthday,
    userPe: userPe.value
  }).then(response => {
    let result: ResponseResult<never>
    if (response.data !== null) {
      result = ResponseResult.fromApiResponse(response.data)
    } else {
      alert('注册失败，服务器发生了错误(与服务器连接丢失!)')
      return
    }
    if (result.operationResult) {
      alert(result.msg)
    } else {
      alert('注册失败，' + result.msg)
    }
  }).catch(error => {
    console.error('注册失败', error)
    alert('注册失败，请稍后重试')
  })
}
</script>
<style scoped>
/* ======== 表单容器 ======== */
.login-form,
.register {
  width: 60%; /* 占页面宽度约50% */
  margin: 2rem auto;
  padding: 2rem;
  border-radius: 16px;
  background: rgba(40, 0, 0, 0.40); /* 半透明卡片 */
  backdrop-filter: blur(6px);
  box-shadow: 0 0 20px rgba(255, 60, 80, 0.2);
  color: #f8f8f8;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

/* ======== 标签和输入框 ======== */
/* 使用列布局让描述在上方，输入框在下方 */
.form-field {
  display: flex;
  flex-direction: column; /* 描述在上，输入框在下 */
  gap: 0.3rem;
}

.form-field label {
  font-weight: 500;
}

/* 短文本输入框，约30字符宽度 */
input[type="text"],
input[type="password"],
input[type="number"],
input[type="date"] {
  width: 100%;
  max-width: 100%;
  padding: 0.5em 0.8em;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(20, 0, 0, 0.5);
  color: #fff;
  font-size: 0.95em;
  box-sizing: border-box;
}

/* 长文本输入框 (用户简介) */
.registerBioInput {
  width: 100%;
  height: clamp(100px, 30vh, 200px);
  padding: 0.6em 0.8em;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(20, 0, 0, 0.5);
  color: #fff;
  font-size: 0.95em;
  resize: vertical;
  overflow-y: auto;
  box-sizing: border-box;
}

/* 提示文字 / 描述 */
.field-description {
  font-size: 0.8em;
  color: #f0c0c0;
}

/* 必填标记 */
.required {
  color: #ff4d4d;
  margin-left: 0.2em;
}

/* 错误提示 */
.error-message {
  color: #ff4d4d;
  font-size: 0.85em;
  margin-top: 0.2rem;
}

/* 按钮 */
.primary-btn,
.backHomeBtn,
.forgotPasswordLink {
  border: none;
  border-radius: 10px;
  padding: 0.7em 1.3em;
  font-size: 1em;
  font-weight: bold;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  margin-top: 0.8rem;
}

.primary-btn {
  background: linear-gradient(145deg, rgba(255, 90, 110, 0.85), rgba(180, 0, 0, 0.85));
}

.backHomeBtn,
.forgotPasswordLink {
  background: rgba(60, 0, 0, 0.5);
}

.primary-btn:hover,
.backHomeBtn:hover,
.forgotPasswordLink:hover {
  filter: brightness(1.15);
  transform: scale(1.03);
}

/* 表单底部链接 */
.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}

.loginToRegisterLink,
.registerToLoginLink {
  color: #ffb0b0;
  cursor: pointer;
  font-size: 0.9em;
  transition: all 0.3s ease;
}

.loginToRegisterLink:hover,
.registerToLoginLink:hover {
  color: #ff5a6e;
  text-decoration: underline;
}

/* ======== 复选框区域 ======== */
.remember-me {
  display: flex;
  flex-direction: column; /* 上下排列 */
  align-items: flex-start;
  gap: 0.3rem;
  margin-top: 0.5rem;
}

.loginRememberLabel {
  display: flex;
  flex-direction: column; /* 文字在上，复选框在下 */
  font-size: 0.95em;
  color: #f0c0c0;
  gap: 0.2rem;
}

.loginRememberCheckbox {
  transform: scale(1.3);
  accent-color: #ff5a6e;
  margin: 0;
}

/* ======== 复选框区域 ======== */
.remember-me {
  display: flex;
  flex-direction: column; /* 上下排列 */
  align-items: flex-start;
  gap: 0.3rem;
  margin-top: 0.5rem;
}

.loginRememberLabel {
  display: flex;
  flex-direction: column; /* 描述在上，复选框在下 */
  font-size: 0.95em;
  color: #f0d0d0;
  gap: 0.3rem;
}

.loginRememberCheckbox {
  width: auto;
  transform: scale(1.2);
  accent-color: #ff5a6e;
  margin: 0;
}

/* ======== 底部按钮区域 ======== */
.bottom-buttons {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 1rem;
}

.primary-btn,
.backHomeBtn,
.forgotPasswordLink {
  padding: 0.7rem 1.5rem;
  font-size: 1em;
  font-weight: 600;
  border-radius: 12px;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s ease;
  text-decoration: none;
  box-shadow: 0 4px 15px rgba(255, 90, 110, 0.3);
}

/* 登录/注册按钮单独一行居中 */
.primary-btn {
  display: block;
  margin: 0.8rem auto;
  background: linear-gradient(135deg, rgba(255, 90, 110, 0.9), rgba(180, 0, 0, 0.9));
}

.backHomeBtn,
.forgotPasswordLink {
  display: inline-block;
  background: rgba(60, 0, 0, 0.6);
  border: 1px solid rgba(255, 100, 120, 0.2);
  color: #ffb0b0;
}

.backHomeBtn:hover,
.forgotPasswordLink:hover,
.primary-btn:hover {
  transform: translateY(-2px);
  filter: brightness(1.1);
}


</style>
